/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Peer;

import FileStructure.BitField;
import FileStructure.FileHandler;
import Peer.peerRequest.*;
import Tools.cons;
import model.PeerEntity;
import java.io.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author user
 */
public class PeerListener implements Runnable{
    PeerEntity peer;
    PeerEntity sender;

    public PeerListener(PeerEntity pe, PeerEntity sender){
        this.peer = pe;
        this.sender = sender;
    }

    public void sendMessage(String msg){
        try {

            PrintWriter out = new PrintWriter(peer.peerSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(peer.peerSocket.getInputStream()));
            out.println(msg);
//            out.close();
//            in.close();
//            this.server.close();

        } catch (IOException ex) {
            Logger.getLogger(PeerListener.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void sendByteArray(byte[] bytes){
        try {

            OutputStream socketOutputStream = peer.peerSocket.getOutputStream();
            socketOutputStream.write(bytes);

        } catch (IOException ex) {
            Logger.getLogger(PeerListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void receiveMessage(){
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(peer.peerSocket.getInputStream()));
            while(!peer.isHandshake){
                
                if ((this.peer.message = in.readLine()) != null) {
                    if (this.peer.message.substring(0, 12).equalsIgnoreCase("19BitTorrent")){
                        System.out.println("menerima handshake");
                        System.out.println(this.peer.message);
                        System.out.println("file name = "+this.peer.message.substring(29,this.peer.message.length()));
                        peer.isHandshake = true;
                    } 
                }

                }
            //System.out.println("read byte = "+ in.read());
            this.receiveByte();
            //}
        } catch (IOException ex) {
            Logger.getLogger(PeerSender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void receiveByte(){
        System.out.println("byte nih");
        System.out.println("buat file");
        
        try {

            InputStream in = peer.peerSocket.getInputStream();
            int b,i=0;
            int count = 0;
            int len = -1;
            boolean stop = false;
            peer.byteLoad = new ArrayList<Byte>();
            while(!stop){
                    b = in.read();
                    peer.byteLoad.add((byte)b);
                    if (peer.byteLoad.size() >= 5){ 
                        count++;
                        if (peer.byteLoad.get(4) == 5 || peer.byteLoad.get(4) == 6 || peer.byteLoad.get(4) == 7){
                            len = peer.byteLoad.get(3);

                        }
                    }
                    if (count == len) stop = true;
                    //System.out.println("byte = " + peer.byteLoad.get(i));
                    i++;
            }
            if(peer.byteLoad.get(4) == 7){
               //berarti ini pieces
               peer.currPieceIdx = peer.byteLoad.get(8);
               int begin = peer.byteLoad.get(12);
               byte[] payload = new byte[cons.pieceLength];

               for(int j=13; j<peer.byteLoad.size(); j++){
                   payload[i] = peer.byteLoad.get(j);
               }

               FileHandler.writePayloadToFile(peer.f, begin, payload);
            }
            
            //}
        } catch (IOException ex) {
            Logger.getLogger(PeerSender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void readPieces(byte[] arr){

    }
    
    public static void main(String[] args){
        //PeerListener pl = new PeerListener(new PeerEntity("127.0.0.1",1234,true));
        //pl.peer.createListener();
        //pl.receiveMessage();
       // pl.peer.createSenderSocket("127.0.0.1", 1235);
        //pl.sendMessage("tes");
    }

    public void run() {
        //throw new UnsupportedOperationException("Not supported yet.");
        this.peer.createListener();
        while(true){
            this.receiveMessage();
           // this.receiveByte();
        }
        //this.sendBitField("test/", "laguku.mp3", "laguku.mp3.torrent");
    }

}
